<template>
  <div>
    <el-container>
      <el-main>
        <div style="width: 70%; margin: 10px auto 0px">
          <el-row class="content" v-loading="loading">
            <el-col :span="4" v-for="(data, index) in datas" :key="index">
              <el-card :body-style="{ padding: '0px', width: '200px' }">
                <img :src="data.poster" class="image" />
                <div style="padding: 14px">
                  <span>{{ data.name }}</span>
                  <div class="bottom clearfix">
                    <div class="price">
                      价格： <span>{{ data.price }}</span>
                    </div>
                    <el-button
                      type="text"
                      class="button"
                      @click="handleBuy(data.id, data.name)"
                      >购买</el-button
                    >
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import * as goods from "@/api/goods";
import * as order from "@/api/order";
import store from "../../store";

export default {
  name: "Home",
  data() {
    return {
      datas: [],
      activeIndex: "1",
      activeIndex2: "1",
      loading: false,
    };
  },
  created() {
    //首页加载商品列表
    this.getList();
  },
  methods: {
    //获取商品列表
    getList() {
      this.loading = true;
      goods.getList().then((response) => {
        if (response.result != null) {
          this.datas = response.result.map((item) => {
            return {
              id: item.id,
              name: item.name,
              description: item.description,
              poster: item.poster,
              price: item.price,
            };
          });
        }
        this.loading = false;
      });
    },

    //购买商品
    handleBuy(id, name) {
      this.$confirm("确定购买" + name + "?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const data = {
          UserId: store.getters.getUserId,
          GoodsId: id,
        };
        order.buy(data).then((response) => {
          this.$message({ type: 'success',message:response.result});
        });
      });
    },
  },
};
</script>
<style scoped>
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 200px;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
.el-card {
  width: 200px;
  margin-top: 10px;
}
.el-menu-demo {
  position: fixed;
  width: 100%;
  z-index: 99;
}
.el-header {
  padding: 0;
}
.price {
  float: left;
}
.price /deep/ span {
  color: coral;
}
</style>